package com.zhengsr.latte.net.callback;

import android.os.Looper;

import com.zhengsr.latte.ui.loader.LatteLoader;
import com.zhengsr.latte.net.RestClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhengshaorui on 2018/4/7.
 * retrofit 回调工具类
 */

public class RequestCallBack implements Callback<String> {
    private static final String TAG = "RequestCallBack";
    private RestClient.Builder mBuilder;
    public RequestCallBack(RestClient.Builder builder) {
        mBuilder = builder;
    }
    private static android.os.Handler sHandler = new android.os.Handler(Looper.myLooper());
    @Override
    public void onResponse(Call call, Response response) {
        if (response.isSuccessful()){
            if (call.isExecuted()){
                if (mBuilder != null){
                    if (mBuilder.listenerAdapter != null){
                        mBuilder.listenerAdapter.onSuccess((String) response.body());
                    }
                }
            }
        }else{
            if (mBuilder != null){
                if (mBuilder.listenerAdapter != null){
                    mBuilder.listenerAdapter.onError(response.code(),response.message());
                }
            }
        }
        sHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LatteLoader.stopDialog();
            }
        },1500);

    }

    @Override
    public void onFailure(Call call, Throwable t) {
        if (mBuilder != null){
            if (mBuilder.listenerAdapter != null){
                mBuilder.listenerAdapter.onFailure(t.toString());
            }
        }
        sHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LatteLoader.stopDialog();
            }
        },1500);
    }

}
